# 各种小函数
import numpy as np

def get_item_append(list,item_torch):
    """提取torch变量的值，并放到数组"""
    item = item_torch.item()
    list.append(item)
    return item


def get_mean(list,print_margin=None):
    """数组后n个数 的平均值"""
    if not print_margin:
        print_margin=len(list)
    return np.mean(list[-print_margin:])

def get_accuracy_one(output_hat,output):
    """精度，1套参数"""
    return (output_hat.argmax(axis=1)==output.reshape(-1)).sum()/output.shape[0]
def get_accuracy_two(output_hat,output,output_hat_2,output_2):
    """精度，2套参数"""
    return ( get_accuracy_one(output_hat,output) + get_accuracy_one(output_hat_2,output_2) )/2


def tqdm_update_epoch_batch_info(tqdm_dataLoader,epoch_info,batch_info,print_margin_batch,
        list_loss,list_accuracy_Y,list_accuracy_location):
    """更新tqdm输出"""
    loss              = get_mean(list_loss             ,print_margin_batch)
    accuracy_Y        = get_mean(list_accuracy_Y       ,print_margin_batch)
    accuracy_location = get_mean(list_accuracy_location,print_margin_batch)
    tqdm_dataLoader.set_description('{}_{}: loss={:>10.5f}, acc_Y={:.3f}, acc_location={:.3f}'.format(
        epoch_info,batch_info,loss,accuracy_Y,accuracy_location ))
    
def get_index_last(list_,target):
    list_reverse = list(list_)[::-1]
    index_reverse = list_reverse.index(target)
    index = len(list_reverse)-1-index_reverse
    return index
